const db = require('../model/database')
const sqlQuery = require('../model/query')

//获取所有账户信息
exports.getAccount = async (req, res) => {
  const page = req.params.page || 1
  const pageSize = req.params.pageSize || 10
  const sql = `SELECT * FROM admin LIMIT ${(page - 1) * pageSize}, ${pageSize}`
  const sql2 = `SELECT * FROM admin`
  let result = await sqlQuery(sql, null, db)
  let result2 = await sqlQuery(sql2, null, db)
  res.send({
    code: 20000,
    msg: '查询成功',
    data: result,
    total: result2.length,
  })
}

//添加用户和权限
exports.addAccount = async (req, res) => {
  const username = req.body.username
  const password = req.body.password
  let roles = req.body.roles.join(',')
  roles[0] === ',' ? roles = roles.substring(1) : roles = roles
  const sql = `select * from admin where username=?`;
  let result = await sqlQuery(sql, (username), db);
  if (result.length > 0) {
    res.send({ code: 40000, msg: '用户名已经存在' })
  } else {
    const sql1 = `insert into admin (username,password,roles) values (?,?,?)`;
    await sqlQuery(sql1, [username, password, roles], db);
    res.send({ code: 20000, msg: '添加成功' })
  }
}

//更新用户信息
exports.updateAccount = async (req, res) => {
  const id = req.body.id
  let roles = req.body.roles.join(',')
  roles[0] === ',' ? roles = roles.substring(1) : roles = roles
  const username = req.body.username
  const password = req.body.password
  const sql1 = `select * from admin where username=? and id not in (${id})`;
  let result = await sqlQuery(sql1, (username), db);
  if (result.length > 0) {
    res.send({ code: 40000, msg: '用户名已经存在' })
  } else {
    const sql2 = `update admin set username=?,password=?,roles=? where id=?`;
    await sqlQuery(sql2, [username, password, roles, id], db);
    res.send({ code: 20000, msg: '修改成功' })
  }
}

//删除账户信息
exports.deleteAccount = async (req, res) => {
  const id = req.params.id
  const sql = `delete from admin where id = ?`
  await sqlQuery(sql, id, db);
  res.send({ code: 20000, msg: '删除成功' })
}


//获取admin_role数据库信息
exports.getRole = async (req, res) => {
  const sql = `SELECT * FROM role_admin`
  let result = await sqlQuery(sql, null, db)
  res.send({
    code: 20000,
    msg: '查询成功',
    data: result,
  })
}



//修改admin_role数据库信息
exports.updateRole = async (req, res) => {
  req.body.rolepage = req.body.rolepage.join(',')
  const id = req.body.id
  const roleInfo = req.body;
  const sql = `update role_admin set ? where id=?`;
  await sqlQuery(sql, [roleInfo, id], db);
  res.send({ code: 20000, msg: '修改成功' })
}

